<template>
  <MkDialogEdit ref='dialogRef' v-model:isEdit='ctx.isEdit' @submit='submit'>
    <MkForm :model='ctx.entity' ref='formRef' formId='BasXueYeYuJing' :col="1">
      <MkSelectBasEntity label="订血医院" v-model='ctx.entity.dingXueYiYuanId' prop='dingXueYiYuanId'
        :isEdit='ctx.isEdit && isNull(ctx.entity.id)' required entity="XieYiYiYuan" @change="changeYiYuan" />
      <MkSelectEnum label="血液大类" v-model='ctx.entity.daLei' prop='daLei' :isEdit='ctx.isEdit && isNull(ctx.entity.id)'
        required enumType="XueYeDaLei" />
      <MkInputNumber label="A型预警值" v-model='ctx.entity.yuJingZhiA' prop='yuJingZhiA' :isEdit='ctx.isEdit' required
        :col="4" />
      <MkInputNumber label="B型预警值" v-model='ctx.entity.yuJingZhiB' prop='yuJingZhiB' :isEdit='ctx.isEdit' required
        :col="4" />
      <MkInputNumber label="O型预警值" v-model='ctx.entity.yuJingZhiO' prop='yuJingZhiO' :isEdit='ctx.isEdit' required
        :col="4" />
      <MkInputNumber label="AB型预警值" v-model='ctx.entity.yuJingZhiAB' prop='yuJingZhiAB' :isEdit='ctx.isEdit' required
        :col="4" />
    </MkForm>
  </MkDialogEdit>
</template>

<script lang='ts' setup>
import { BasYueXueYuJingApi, BasYueXueYuJingOutput } from '/@/api/bas/BasYueXueYuJing';
import { getOrgName } from '/@/stores/baseInfo';
import { isNull, clog } from '/@/utils';

const emits = defineEmits(['query'])
const ctx = reactive({
  isEdit: false,
  isAdd: false,
  entity: {} as BasYueXueYuJingOutput,
});

const dialogRef = ref();
const formRef = ref();

/** 打开弹框 */
const open = async (row: BasYueXueYuJingOutput) => {
  dialogRef.value.show();
  if (isNull(row?.id)) {
    ctx.isEdit = true;
    ctx.isAdd = true;
    ctx.entity = {} as BasYueXueYuJingOutput;
  } else {
    ctx.isAdd = false;
    ctx.isEdit = false;
    ctx.entity = JSON.parse(JSON.stringify(row));
  }
};

// 修改订血医院id时自动带出订血医院名称
const changeYiYuan = (val: number) => {
  clog('val', getOrgName(val))
  ctx.entity.dingXueYiYuan = getOrgName(val);
}

const close = () => {
  dialogRef.value?.close();
  emits('query')
};


const submit = async () => {
  if (!ctx.isEdit) {
    close();
    return;
  }
  // 表单验证
  const validate = await formRef?.value?.validate();
  if (!validate) return;
  if (ctx.isAdd) {
    await BasYueXueYuJingApi.add(ctx.entity);
  } else {
    await BasYueXueYuJingApi.update(ctx.entity);
  }
  close();
};

defineExpose({ open })
</script>